import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

def train_naive_bayes(X_train, y_train):
    # 计算先验概率 P(Y=c)
    classes = np.unique(y_train)
    priors = {c: sum(y_train == c) / len(y_train) for c in classes}

    # 计算条件概率 P(X=x|Y=c)
    likelihoods = {}
    for c in classes:
        X_c = X_train[y_train == c]
        likelihoods[c] = {
            i: (X_c[:, i].mean(), X_c[:, i].std()) for i in range(X_train.shape[1])
        }

    return priors, likelihoods

def predict_naive_bayes(X, priors, likelihoods):
    # 计算 P(Y=c|X=x) ∝ P(Y=c) * P(X=x|Y=c)
    posteriors = np.zeros(X.shape[0])
    for c in priors:
        prior = priors[c]
        likelihood = np.zeros(X.shape[0])
        for i in range(X.shape[1]):
            mean, std = likelihoods[c][i]
            likelihood += np.log(1 / (np.sqrt(2 * np.pi) * std)) \
                          - (X[:, i] - mean) ** 2 / (2 * std ** 2)
        posteriors_c = np.log(prior) + likelihood
        posteriors = np.vstack([posteriors, posteriors_c])
    return np.argmax(posteriors[1:].T, axis=1)

# 加载 iris 数据集
iris = load_iris()
X = iris.data
y = iris.target

# 将数据集划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 训练模型并进行预测
priors, likelihoods = train_naive_bayes(X_train, y_train)
y_pred = predict_naive_bayes(X_test, priors, likelihoods)

# 计算模型的准确率
accuracy = np.mean(y_pred == y_test)

# 输出实验结果
print(f"模型的准确率为 {accuracy:.2%}")
